import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { products } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function GET() {
  try {
    const allProducts = await db.select().from(products);
    return NextResponse.json(allProducts);
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch products' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const [newProduct] = await db
      .insert(products)
      .values({
        name: body.name,
        description: body.description,
        price: body.price,
        sku: body.sku,
        imageUrl: body.imageUrl,
        category: body.category,
      })
      .returning();

    return NextResponse.json(newProduct, { status: 201 });
  } catch (error: any) {
    console.error('Database error:', error);
    
    if (error.message?.includes('UNIQUE constraint failed')) {
      return NextResponse.json(
        { error: 'SKU已存在，请使用唯一的SKU编号' },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { error: '创建产品失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}